package com.company.tips.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.company.corelib.facade.CategoryFacade;
import com.company.corelib.model.Category;

@Controller
@RequestMapping("admin/category/")
public class CategoryController {
	private CategoryFacade categoryFacade = new CategoryFacade();
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public ModelAndView index() {
		System.err.println("redirect to list category");
		ModelAndView model = new ModelAndView();
		model.addObject("categories",categoryFacade.getAllCategory());
		model.setViewName("admin/category/list");
		return model;
	}
	@RequestMapping(value = "create", method = RequestMethod.POST)
	public ModelAndView create(
			@RequestParam(value="catcode", required=false) String catcode,
			@RequestParam(value="catname", required=false) String catname,
			@RequestParam(value="catdescription", required=false) String description){
		ModelAndView model = new ModelAndView();
		categoryFacade.create(catcode, catname, description);
		model.addObject("categories",categoryFacade.getAllCategory());
		if(catcode != null){
			model.setViewName("redirect:list");
		}else{
			model.setViewName("/admin/category/create");
		}
		return model;
	}
	
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	public ModelAndView update(
			@RequestParam(value="catid", required=false) String id,
			@RequestParam(value="catcode", required=false) String catcode,
			@RequestParam(value="catname", required=false) String catname,
			@RequestParam(value="catdescription", required=false) String description){
		System.err.println("catID = " + id);
		ModelAndView model = new ModelAndView();
		Category category = categoryFacade.getCategoryById(id);
		if(catcode != null){
			model.addObject("category",categoryFacade.getAllCategory());
			category.setCode(catcode);
			category.setName(catname);
			category.setDescription(description);
			categoryFacade.update(category);
			model.setViewName("redirect:list");
		}else{
			model.addObject("category",category);
			model.setViewName("/admin/category/edit");
		}
		return model;
	}
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public ModelAndView delete(
			@RequestParam(value="catid", required=true) String id,
			@RequestParam(value="catcode", required=false) String catcode){
		System.err.println("catID = " + id);
		ModelAndView model = new ModelAndView();
		categoryFacade.delete(id);
		model.setViewName("redirect:list");
		return model;
	}
}
